package com.zj.juc.study.interrupted;

import java.util.concurrent.TimeUnit;

/**
 * @author 自己的名字
 * @version 1.0.0
 * @ClassName ThreadRunningInterrupted
 * @Description 线程运行中sleep后interrupt
 * @createTime 2024年12月26日 21:47
 */
public class ThreadRunningInterrupted
{
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            while (true){
                System.out.println("go go go");
                if (Thread.currentThread().isInterrupted()){
                    System.out.println(Thread.currentThread().getName()+" interrupt");
                    break;
                }

                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    //解决在打断抛出异常后无法退出循环问题
                    Thread.currentThread().interrupt();
                    e.printStackTrace();
                }
            }
        }, "t1");

        thread.start();

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(()->{
            thread.interrupt();
        },"t2").start();


    }
}
